import { _decorator, Button, CCBoolean, CCInteger, Component, Node, tween, UIOpacity, Vec3 } from 'cc';
import Utils from '../utils/Utils';
const { ccclass, property } = _decorator;

@ccclass('UIHand')
export class UIHand extends Component {
    // 静态属性，记录当前显示的 UIHand 实例
    private static _currentHand: UIHand | null = null;
    @property({ type: Button, displayName: '绑定按钮' }) bindingBtnList: Button[] = [];
    @property(Node) hand: Node = null!;
    @property(CCBoolean) showHand: boolean = true;
    @property({ type: CCInteger, displayName: '显示手指延时(秒)', min: 0 })
    private delayTime: number = 3;
    private _handShowTween: any = null;
    private op: UIOpacity = null;

    protected onLoad(): void {
        this.op = this.node.getComponent(UIOpacity);
        this.op.opacity = this.showHand ? 255 : 0;
        Utils.AutoScale(this.node);

        this.bindingBtnList.forEach(btn => {
            btn.node.on(Button.EventType.CLICK, () => {
                this.stopHandShowTween();
            }, this);
        });
    }

    protected onEnable(): void {
        this.startHandShowTween();
    }

    protected onDisable(): void {
        this.stopHandShowTween();
    }

    /** 开始计时 */
    public startHandShowTween() {
        // 如果有其他 UIHand 正在显示，先隐藏它
        if (UIHand._currentHand && UIHand._currentHand !== this) {

            UIHand._currentHand.node.active = false;
            UIHand._currentHand = null;
            // console.log("有其他手指正在显示，先隐藏它", UIHand._currentHand.node.name);
            // this.scheduleOnce(() => {
            //     this.startHandShowTween();
            // }, this.delayTime);
            // return;
        }

        UIHand._currentHand = this;
        if (this._handShowTween) {
            this._handShowTween.stop();
            this._handShowTween = null;
        }
        this._handShowTween = tween({})
            .delay(this.delayTime)
            .call(() => {
                this.op.opacity = 255;
            })
            .start();
    }

    /** 停止计时 */
    public stopHandShowTween() {
        UIHand._currentHand = null;
        this.op.opacity = 0;
        if (this._handShowTween) {
            this._handShowTween.stop();
            this._handShowTween = null;
        }
        // 如果自己是当前显示的实例，则清空
        if (UIHand._currentHand === this) {
            UIHand._currentHand = null;
        }
    }
}


